<template>
  <div class="room-detail">
    <!-- 左侧房间信息 -->
    <div class="room-info">
      <!-- 图片轮播 -->
      <el-carousel height="500px" v-if=" room?.roomImages?.length" class="image-carousel">
        <el-carousel-item v-for="image in room.roomImages" :key="image">
          <img :src="image" class="carousel-image">
        </el-carousel-item>
      </el-carousel>

      <div class="info-content">
        <h1 class="room-title">{{ room.name }}</h1>
        <div class="price">￥{{ room.price }} /月</div>
        <div class="description">房间介绍：{{ room.description }}</div>
        <div class="owner_phone">房东联系方式：{{ room.owner?.phone || '暂无'}}</div>

        <!--收藏按钮-->
        <div class="favorite-section">
          <el-button
              :type="data.isCollection ? 'warning' : 'info'"
              @click="handleCollection(data.user.id, room.id)"
              :icon="data.isCollection ? StarFilled : Star"
              v-if="data.user?.role === 'user'"
          >
            {{ data.isCollection ? '取消收藏' : '收藏房间' }}
          </el-button>
        </div>


        <!-- 房间详细信息 -->
        <div class="details">
          <div class="detail-item">
            <el-icon><Location /></el-icon>
            <span>位置：{{ room.area }}</span>
          </div>
          <div class="detail-item">
            <el-icon><House /></el-icon>
            <span>面积：{{ room.size }}平米</span>
          </div>
          <!-- 其他房间信息 -->
        </div>


        <!-- 评论区 -->
        <div class="comments-section">
          <div class="comments-header">
            <h2 class="comments-title">房客评价</h2>
            <el-button type="primary" @click="showCommentDialog" class="add-comment-btn" v-if="data.user?.role === 'user'">
              <el-icon><Edit /></el-icon>写评论
            </el-button>
          </div>

          <!-- 评论列表 -->
          <div class="comments-list" v-if="comments.length">
            <div v-for="comment in comments" :key="comment.id" class="comment-item">
              <div class="comment-user">
                <el-avatar :size="50" :src="comment.avatar || defaultAvatar"></el-avatar>
                <div class="user-info">
                  <div class="username">{{ comment.name || '匿名用户' }}</div>
                  <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
                </div>
              </div>

              <div class="comment-content">
                <div class="comment-text">{{ comment.content }}</div>

                <!-- 如果是当前用户的评论，显示删除按钮 -->
                <div class="comment-actions" v-if="comment.userId === data.user.id">

                      <el-button type="danger" @click="deleteComment(comment.id)" v-if="data.user?.role === 'user'">
                        <el-icon><Delete /></el-icon>删除
                      </el-button>

                </div>
              </div>
            </div>
          </div>

          <!-- 无评论时显示 -->
          <div v-else class="no-comments">
            <el-empty description="暂无评论" />
          </div>

          <!-- 添加评论对话框 -->
          <el-dialog
              v-model="dialogVisible"
              title="发表评论"
              width="500px"
              :before-close="handleClose"
          >
            <el-form :model="commentForm" ref="commentFormRef" :rules="commentRules">
              <el-form-item prop="content">
                <el-input
                    v-model="commentForm.content"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入您的评论内容..."
                />
              </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitComment">
            发表评论
          </el-button>
        </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>

    <!-- 右侧预约看房和租赁表单 -->
    <div class="action-section" v-if="data.user?.role === 'user'">
      <!-- 操作选择按钮 -->
      <div class="action-buttons">
        <el-button 
          type="primary" 
          :class="{ 'active-button': activeForm === 'appointment' }" 
          @click="activeForm = 'appointment'"
        >
          预约看房
        </el-button>
        <el-button 
          type="success" 
          :class="{ 'active-button': activeForm === 'rental' }" 
          @click="activeForm = 'rental'"
        >
          在线租赁
        </el-button>
      </div>

      <!-- 预约看房表单 -->
      <el-card class="form-card" v-if="activeForm === 'appointment'">
        <h2 class="form-title">预约看房</h2>
        <el-form :model="appointmentForm" label-width="100px" :rules="rules" ref="appointmentFormRef">
          <el-form-item label="预约日期" prop="appointmentDate">
            <el-date-picker
                v-model="appointmentForm.appointmentDate"
                type="date"
                placeholder="选择看房日期"
                :disabled-date="disabledDate"
                value-format="YYYY-MM-DD"
                class="form-input"
            />
          </el-form-item>

          <el-form-item label="预约时间" prop="appointmentTime">
            <el-time-select
                v-model="appointmentForm.appointmentTime"
                start="09:00"
                step="00:30"
                end="18:00"
                placeholder="选择看房时间"
                class="form-input"
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="appointmentForm.phone" placeholder="请输入您的联系电话" class="form-input"/>
          </el-form-item>

          <el-form-item label="备注信息" prop="remark">
            <el-input
                v-model="appointmentForm.remark"
                type="textarea"
                placeholder="请输入备注信息（选填）"
                :rows="3"
                class="form-input"
            />
          </el-form-item>

          <el-button type="primary" @click="submitAppointment" class="submit-btn">
            提交预约
          </el-button>
        </el-form>
      </el-card>

      <!-- 租赁表单 -->
      <el-card class="form-card" v-if="activeForm === 'rental'">
        <h2 class="form-title">创建租赁订单</h2>
        <el-form :model="rentalForm" label-width="100px" :rules="rentalRules" ref="rentalFormRef">
          <el-form-item label="入住时间" prop="inTime">
            <el-date-picker
                v-model="rentalForm.inTime"
                type="date"
                placeholder="选择入住日期"
                :disabled-date="disabledRentalDate"
                value-format="YYYY-MM-DD"
                class="form-input"
            />
          </el-form-item>

          <el-form-item label="租赁月数" prop="months">
            <el-input-number
                v-model="rentalForm.months"
                :min="1"
                :max="24"
                class="form-input"
                @change="calculateOutTime"
            />
          </el-form-item>

          <el-form-item label="退房时间">
            <div class="calculated-time">{{ calculatedOutTime }}</div>
          </el-form-item>

          <el-form-item label="总金额">
            <div class="total-amount">￥{{ calculateTotalAmount }}</div>
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="rentalForm.phone" placeholder="请输入您的联系电话" class="form-input"/>
          </el-form-item>

          <el-button type="success" @click="submitRental" class="submit-btn">
            提交订单
          </el-button>
        </el-form>
      </el-card>
    </div>

    <!-- 房东提示信息 -->
    <div class="booking-form" v-else-if="data.user?.role === 'owner'">
      <el-alert type="info" show-icon :closable="false">
        <template #title>
          <span style="font-size: 16px">作为房东，您可以管理房源但不能预约其他房东的房间</span>
        </template>
      </el-alert>
    </div>
  </div>

</template>

<script setup>
import {ref, onMounted, reactive, computed} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Star, StarFilled, Location, House, Edit, Delete} from '@element-plus/icons-vue'
import request from '@/utils/request';
import dayjs from 'dayjs'

const route = useRoute();
const router = useRouter();
const roomId = route.params.roomId;

const data = reactive({
  user:JSON.parse(localStorage.getItem('localStorageUser')),
  isCollection:false,//收藏状态
})

// 当前激活的表单
const activeForm = ref('appointment');

// 房间信息
const room = ref({});

// 评论相关
const comments = ref([]);
const dialogVisible = ref(false);
const commentForm = ref({ content: '' });
const commentFormRef = ref(null);
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
// 评论表单验证规则
const commentRules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 2, max: 200, message: '评论长度在 2 到 200 个字符', trigger: 'blur' }
  ]
};

// 预约表单
const appointmentFormRef = ref(null);
const appointmentForm = ref({
  appointmentDate: '',
  appointmentTime: '',
  phone: '',
  remark: ''
});

// 表单验证规则
const rules = {
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 租赁表单
const rentalFormRef = ref(null);
const rentalForm = ref({
  inTime: '',
  months: 1,
  phone: ''
});

// 租赁表单验证规则
const rentalRules = {
  inTime: [
    { required: true, message: '请选择入住日期', trigger: 'change' }
  ],
  months: [
    { required: true, message: '请选择租赁月数', trigger: 'change' },
    { type: 'number', min: 1, message: '最少租期为1个月', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

const checkCollection = async () => {
  try {
    const res = await request.get('/collection/isCollection', {
      params: {
        userId: data.user.id,
        roomId: roomId
      }
    });
    console.log('checkCollection的res值为：',res)
    if (res.code === '200'){
      data.isCollection = res.data;
    }

  }catch (error){
    ElMessage.error('获取收藏状态失败',error);
  }
}

const handleCollection = async () => {
  if (!data.user){
    ElMessage.error('请先登录');
    return router.push('/login');
  }
  try {
    if (data.isCollection) {
      // 添加确认对话框
      await ElMessageBox.confirm('确定要取消收藏该房间吗？', '取消收藏确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });

      // 取消收藏
      const res = await request.delete('/collection/delete', {
        params: {
          userId: data.user.id,
          roomId: roomId
        }
      });

      if (res.code === '200') {
        ElMessage.success('取消收藏成功');
        data.isCollection = false;
      }

    } else {
      // 添加收藏
      const res = await request.post('/collection/add', {
        userId: data.user.id,
        roomId: roomId
      });
      if (res.code === '200') {
        ElMessage.success('收藏成功');
        data.isCollection = true;
      }
    }
  } catch (error) {
    if (error !== 'cancel'){
      ElMessage.error('操作失败');
      console.error('收藏操作失败:', error);
    }

  }

}


// 获取房间详情
const getRoomDetail = async () => {
  try {
    // 确保 roomId 是数字类型
    const numericRoomId = parseInt(roomId);
    console.log('获取房间详情，转换后的 roomId:', numericRoomId, '类型:', typeof numericRoomId);

    const res = await request.get('/room/selectAll', {
      params: {
        roomId: numericRoomId
      }
    });

    if (res.code === '200') {
      const roomData = res.data;
      console.log('roomData的值为：',roomData)
      if (roomData && roomData.length > 0) {
        room.value = roomData[0];
        console.log('room.value的值为：',room.value)
      } else {
        ElMessage.error('房间不存在');
        router.go(-1);//返回上一页
      }
    }
  } catch (error) {
    ElMessage.error('获取房间信息失败');
    console.error('获取房间信息失败:', error);
  }
};


// 获取评论列表
const getComments = async () => {
  try {
    const res = await request.get('/comment/selectAll', {
      params: { roomId }
    });
    if (res.code === '200') {
      comments.value = res.data;
    }
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 显示评论对话框
const showCommentDialog = () => {
  dialogVisible.value = true;
};

// 提交评论
const submitComment = async () => {
  if (!commentFormRef.value) return;

  await commentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.post('/comment/add', {
          roomId,
          content: commentForm.value.content,
          userId: data.user.id
        });
        if (res.code === '200') {
          ElMessage.success('评论发表成功');
          dialogVisible.value = false;
          commentForm.value.content = '';
          getComments();
        }
      } catch (error) {
        ElMessage.error('评论发表失败');
      }
    }
  });
};

// 删除评论
const deleteComment = async (commentId) => {

    ElMessageBox.confirm('确定要删除该评论吗？', '提示', {type: 'warning'}).then(()=>{

      request.delete('/comment/delete', {
        params:{
          id:commentId
        }
      }).then(res =>{
        if (res.code === '200'){
          ElMessage.success('删除评论成功')
          getComments()
        }else {
          ElMessage.error(res.msg)
        }
      })
    }).catch()
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 对话框关闭处理
const handleClose = (done) => {
  commentForm.value.content = '';
  done();
};

// 提交预约
const submitAppointment = async () => {
  if (!appointmentFormRef.value) return;

  await appointmentFormRef.value.validate(async (valid) => {
    if (valid) {
        const appointmentData = {
          userId: data.user.id,
          roomId: roomId,
          time: `${appointmentForm.value.appointmentDate} ${appointmentForm.value.appointmentTime}`,
          phone: appointmentForm.value.phone,
          remark: appointmentForm.value.remark
        };

        const res = await request.post('/appointment/add', appointmentData);
        if (res.code === '200') {
          ElMessage.success('预约成功，房东稍后会与您联系');
          router.push('/front_page/appointment'); // 跳转到我的预约页面
        }else {
          ElMessage.error(res.msg)
        }

    }
  });
};

// 禁用日期（今天之前的日期）
const disabledDate = (date) => {
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 0, 0, 0)
  return date < tomorrow;
};

// 计算退房时间
const calculatedOutTime = computed(() => {
  if (!rentalForm.value.inTime) return '请先选择入住时间';
  const inTime = dayjs(rentalForm.value.inTime);
  return inTime.add(rentalForm.value.months, 'month').format('YYYY-MM-DDTHH:mm:ss');
});

// 计算总金额
const calculateTotalAmount = computed(() => {
  return room.value.price * rentalForm.value.months;
});

// 禁用租赁日期（今天之前的日期）
const disabledRentalDate = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return date < today;
};

// 提交租赁订单
const submitRental = async () => {
  if (!rentalFormRef.value) return;

  await rentalFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const orderData = {
          userId: data.user.id,
          ownerId: room.value.ownerId,
          roomId: room.value.id,
          inTime: rentalForm.value.inTime + ' 00:00:00',
          outTime: calculatedOutTime.value.split('T')[0] + ' 00:00:00',
          status: '0',
          payNum: calculateTotalAmount.value
        };

        const res = await request.post('/orders/add', orderData);
        if (res.code === '200') {
          ElMessage.success('租赁订单创建成功');
          router.push('/front_page/order'); // 跳转到订单页面
        } else {
          ElMessage.error(res.msg || '创建订单失败');
        }
      } catch (error) {
        console.error('创建订单失败:', error);
        ElMessage.error('创建订单失败');
      }
    }
  });
};

onMounted(async() => {
  await getComments();
  await getRoomDetail();
  if(data.user) await checkCollection()
});
</script>

<style scoped>
.room-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
}

/* 图片轮播样式 */
.image-carousel {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 房间信息样式 */
.info-content {
  padding: 24px 0;
}

.room-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 16px;
}

.price {
  color: #f56c6c;
  font-size: 28px;
  font-weight: bold;
  margin: 16px 0;
}

.description {
  font-size: 16px;
  color: #5a6a7f;
  line-height: 1.6;
  margin: 16px 0;
}

.owner_phone {
  font-size: 16px;
  color: #5a6a7f;
  margin: 16px 0;
}

.details {
  margin: 24px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin: 12px 0;
  font-size: 16px;
  color: #5a6a7f;
}

.detail-item .el-icon {
  margin-right: 12px;
  font-size: 20px;
  color: #409EFF;
}

/* 预约表单样式 */
.booking-form {
  position: sticky;
  top: 20px;
}

.form-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.form-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 24px;
  text-align: center;
}

.form-input {
  width: 100%;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 16px;
  border-radius: 8px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .room-detail {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .room-info, .booking-form {
    grid-column: 1;
  }

  .booking-form {
    position: static;
  }

  .image-carousel {
    height: 300px !important;
  }

  .room-title {
    font-size: 24px;
  }

  .price {
    font-size: 24px;
  }
}

/* 添加一些动画效果 */
.form-card {
  transition: transform 0.3s ease;
}

.form-card:hover {
  transform: translateY(-5px);
}

.submit-btn {
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 美化滚动条 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 评论区样式 */
.comments-section {
  margin-top: 40px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.comments-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.comment-item {
  padding: 20px;
  border-radius: 8px;
  background: #f8f9fa;
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 500;
  color: #2c3e50;
}

.comment-time {
  font-size: 14px;
  color: #909399;
}

.comment-content {
  margin-left: 66px;
  margin-top: 12px;
}

.comment-text {
  line-height: 1.6;
  color: #5a6a7f;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.no-comments {
  padding: 40px 0;
  text-align: center;
}

.favorite-section {
  margin: 16px 0;
}

.favorite-section .el-button {
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.favorite-section .el-button:hover {
  transform: translateY(-2px);
}

/* 操作按钮样式 */
.action-section {
  position: sticky;
  top: 20px;
}

.action-buttons {
  display: flex;
  margin-bottom: 16px;
  gap: 10px;
}

.action-buttons .el-button {
  flex: 1;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.active-button {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 租赁表单样式 */
.calculated-time, .total-amount {
  font-size: 16px;
  color: #606266;
  line-height: 40px;
  font-weight: bold;
}

.total-amount {
  color: #f56c6c;
  font-size: 20px;
}
</style>